#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

pthread_mutex_t mylock;
pthread_cond_t mycond;

int num[] = {1, 2, 3, 4, 5};

void *thread1_fun(void *args) {
    int i;
    /*
    //仅有锁时，交替执行
    for(i = 0; i < 5; i++) {
        pthread_mutex_lock(&mylock);
        printf("thread1:%d\n", num[i]);
        pthread_mutex_unlock(&mylock);
        sleep(1);
    }
    */
    pthread_mutex_lock(&mylock);
    for(i = 0; i < 5; i++) {
        printf("thread1:%d\n", num[i]);
        sleep(1);
    }
    pthread_mutex_unlock(&mylock);
    pthread_cond_signal(&mycond);
    sleep(1);
    pthread_exit(NULL);
    return 0;
}

void *thread2_fun(void *args) {
    int i;
    /*
    //仅有锁时，交替执行
    for(i = 4; i >= 0; i--) {
        pthread_mutex_lock(&mylock);
        printf("thread2:%d\n", num[i]);
        pthread_mutex_unlock(&mylock);
        sleep(1);
    }
    */
    pthread_mutex_lock(&mylock);
    pthread_cond_wait(&mycond, &mylock);
    for(i = 4; i >= 0; i--) {
        printf("thread2:%d\n", num[i]);
        sleep(1);
    }
    pthread_mutex_unlock(&mylock);
    pthread_exit(NULL);
}

int main(int argc, const char *argv[]) {
    pthread_t thread1, thread2;

    if(pthread_create(&thread1, NULL, thread1_fun, NULL) != 0) {
        perror("pthread_create thread1\n");
        _exit(1);
    }
    if(pthread_create(&thread2, NULL, thread2_fun, NULL) != 0) {
        perror("pthread_create thread2\n");
        _exit(1);
    }
    if(pthread_mutex_init(&mylock, NULL) != 0) {
        perror("pthread_mutex_init error\n");
        _exit(1);
    }
    if(pthread_cond_init(&mycond, NULL) != 0) {
        perror("pthread_cond_init error\n");
        _exit(1);
    }

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

}
